<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Released under the MIT License.
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------

namespace app\app\controller;

use cmf\controller\AdminBaseController;
use think\Db;
use app\admin\model\AdminMenuModel;
use think\Validate;
class ShopController extends AdminBaseController
{
    public function index()
    {
        $where = array();
        $params = $this->param();
        $status = 0;
        if(isset($params['name'])){
            $where[] = ['t1.name','like','%'.$params['name'].'%'];
        }
        if(isset($params['status']) && $params['status']){
            $where[] = ['t1.status','eq',$params['status']];
            $status = $params['status'];
        }
        $shop = db::name('app_shop')->alias('t1')
            ->join('user t2','t2.id = t1.admin_id')
            ->field('t1.*,t2.user_login')
            ->where($where)
            ->paginate(10,false,
            ['query'=>$params])->each(function($item, $key){
                if($item['puid']){
                    $item['pname'] = db::name('app_user')->where('id',$item['puid'])->value('nickname');
                }else{
                    $item['pname'] = '无';
                }

                return $item;
        });
        $this->assign('shop',$shop);
        $this->assign('status',$status);
        $shop->appends($params);  //分页条件
        $this->assign('page', $shop->render());
        return $this->fetch();
    }

    public function add()
    {
        if($_POST){
            $validate = new Validate([
                'name'  => 'require',
                'lat'  => 'require',
                'lng'  => 'require',
                'address'  => 'require',
            ]);
            if(!$validate->check($_POST)){
                $this->error($validate->getError());
            }
            $_POST['addtime'] = date('Y-m-d H:i:s',time());
            $_POST['status'] = 1;//后台添加 默认审核通过
            //判断当前选择的管理账号 是否已经有店铺
            if(db::name('app_shop')->where('admin_id',$_POST['admin_id'])->find()){
                $this->error('当前管理员已有店铺,请重新选择或者新添加管理员');
            }
            $res = db::name('app_shop')->insert($_POST);
            if($res){
                $this->success('添加成功');
            }else{
                $this->error('添加失败');
            }
        }
        //查询不是超级管理员的账户
        $map[] = ['t2.role_id','neq',1];
        $login_user = db::name('user')->alias('t1')
            ->join('role_user t2','t2.user_id = t1.id')
            ->field('t1.id,t1.user_login')
            ->where($map)
            ->select();
        $this->assign('login_user',$login_user);
        return $this->fetch();
    }
    public function edit()
    {
        $id = $this->param('id');
        if($_POST){
            $validate = new Validate([
                'name'  => 'require',
                'lat'  => 'require',
                'lng'  => 'require',
                'address'  => 'require',
            ]);
            if(!$validate->check($_POST)){
                $this->error($validate->getError());
            }

            $res = db::name('app_shop')->update($_POST);
            if($res){
                $this->success('修改成功');
            }else{
                $this->error('修改失败');
            }

        }else{
            $find = db::name('app_shop')->find($id);
            $this->assign('info',$find);
            return $this->fetch();
        }
    }
    public function delete()
    {
        $id = $this->param('id');
        $res = db::name('app_shop')->delete($id);
        if($res){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }
    //店铺商品
    public function goods()
    {
        $params = $this->param();
        $id = $params['id'];
        $shopgoods = db::name('app_shopgoods');
        $goods = $shopgoods->where('shop_id',$id)->column('goods_id');
        if($_POST){
            if(!$_POST['goodsid']){
                $this->error('请选择商品!!!');
            }
            $ids = explode(',',rtrim($_POST['goodsid'],','));
            $data = array();
            //先查询店铺商品表 是否有数据 当店铺的数据
            if(!$goods){
                //不存在直接添加数据
                foreach($ids as $k=>$v){
                    $data[] = ['shop_id'=>$id,
                                'goods_id'=>$v,
                                'addtime'=>date('Y-m-d H:i:s',time())
                            ];
                }
                $res = $shopgoods->insertAll($data);
                if($res){
                    $this->success('成功');
                }else{
                    $this->error('失败');
                } 
            }else{
                //比对数据库和新提交的数据
                Db::startTrans(); //启动事务
                try {
                    //比对新提交的商品id 在数据库是否存在  如果有 就不添加
                    foreach($ids as $k=>$v){
                        //新添加的商品不存在  添加
                        if(!in_array($v,$goods)){
                            $data['shop_id'] = $id;
                            $data['goods_id'] = $v;
                            $data['addtime'] = date('Y-m-d H:i:s',time());
                            // $res = $shopgoods->insert($data[$k]);
                            // if(!$res[$k]){
                            //     throw new \Exception('id为'.$v.'的商品添加失败');
                            // }
                            $datas[] = $data;
                        }
                    }
                    $res = $shopgoods->insertAll($datas);
                    if(!$res){
                        throw new \Exception('更新失败');
                    }
                    //然后在比对 数据库的商品id 新提交过来的数据没有  则删除
                    foreach($goods as $kk=>$vv){
                        if(!in_array($vv,$ids)){
                            $res1 = db::name('app_shopgoods')->where(array('shop_id'=>$id,'goods_id'=>$vv))->delete();
                            if(!$res1){
                                throw new \Exception('id为'.$vv.'的商品删除失败');
                            }
                        }
                    }
                    Db::commit(); //提交事务
                } catch (\Exception $e) {
                        Db::rollback(); //回滚事务
                        $this->error($e->getMessage());
                }
                $this->success('更新成功');
            }
        }
        //查询出平台所有商品 及分类
        $list = db::name('good_cate')->field('id,name')->where('status',1)->select();
        $list = $list->all();//奇葩不能之直接赋值  
        foreach($list as $k=>$v){
            $list[$k]['data'] = db::name('goods')
                ->field('id,name,img,price')
                ->where(array('status'=>1,'cateId'=>$v['id']))
                ->select();
        }
        //查询当前店铺的商品
        $this->assign('goods',implode(',',$goods));
        $this->assign('id',$id);
        $this->assign('list',$list);
        return $this->fetch();
    }
}
